var index = {

    /**
     * 当前显示的ID
     */
    nowTabId: 0,
    /**
     * 初始化快捷键
     */
    initKey: function () {
        document.onkeydown = function (e) {
            var keyCode = e.keyCode || e.which || e.charCode;
            var ctrlKey = e.metaKey;
            // console.log(ctrlKey,keyCode);
            if (ctrlKey && keyCode == 82) {//刷新 mac
                e.preventDefault();
                return false;
            } else if (ctrlKey && keyCode == 83) {//保存操作

            }

        }
    },
    /**
     * 初始化加载
     */
    init: function () {
        this.checkGooge();
        this.initKey();
        this.loadWorkbench();
        if ($(window).width() <= 768) {
            $('.layout-zxw-left').css('width', 0)
            $('.layui-icon-shrink-right').removeClass('layui-icon-shrink-right').addClass('layui-icon-spread-left');
        }

        //加载数据信息
        $.ajax({
            url: '../../base.json',
            type: "GET",
            dataType: "json",
            success: function (result) {
                // console.log("结果=====》",result);
                $('.layui-zxw-logo').text(result.sys_name);
                window.document.title = result.sys_name;
                $('.layout-zxw-footer').html(result.foot_name);
            }
        });


        $('#leftScoll').niceScroll({
            touchbehavior: true,
            scrollspeed: 200,
            mousescrollstep: 200
        });
        $('.layui-tab-title').niceScroll({
            touchbehavior: true,
            scrollspeed: 200,
            mousescrollstep: 200,
            autohidemode: 'cursor',
            cursoropacitymax: 0,
            spacebarenabled: false,
            touchbehavior: true
        });

        //只有本地才加载示例页面
        if (window.location.host.indexOf("localhost") >= 0) {
            this.loadTab('0', '示例', 'simpleCode.html', false);
        }

        //如果存在首页就加载首页信息，否则不加载首页
        $.ajax({
            url: '../../html/home.html',
            type: "GET",
            dataType: "html",
            success: function (result) {
                index.loadTab('1', '<i class="layui-icon layui-icon-home"></i>', 'home.html', false);
            }
        });

        this.loadingMenu();
        //左边菜单切换
        index.leftChange();
        index.jianting_tab();
        index.tabClose();
        index.jiantingshurukuang();

        $('.changeOwnInfo').click(function () {
            njzxw.openWindow({
                id: 'myUserInfo',
                title: '个人信息',
                content: 'user.html?id='
            });
        });
        $('.changePassWord').click(function () {
            njzxw.openWindow({
                id: 'myPasswordUserInfo',
                title: '密码修改',
                content: 'password.html?id='
            });

        });
        $('.showmyinfo').click(function () {
            njzxw.openWindow({
                id: 'myUserInfo',
                title: '个人信息',
                content: 'user.html?id=',
                btn: []
            });
        });
        $('.nameUsera b').text(njzxw.cookie.getCookie('name'));
        $('.nameUsera img').attr('src', njzxw.cookie.getCookie('head_img'));
    },
    /**
     * 最大化当前窗口
     */
    maxFrameTab: function () {
        $('.layui-tab-content .layui-show iframe').addClass('max_frame_tab');
    },
    restoreFrameTab: function () {
        $('.layui-tab-content .layui-show iframe').removeClass('max_frame_tab');
    },
    isMacFrame: function () {
        return $('.layui-tab-content .layui-show iframe').hasClass('max_frame_tab');
    },
    checkGooge: function () {
        if (!!window.ActiveXObject || "ActiveXObject" in window) {
            layer.msg('<div style="text-align: center;" >为了最佳体验，系统推荐您是要谷歌浏览器，如您未安装，请点击<a target="view_window" style="color: blue; " href="https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=2&tn=baiduhome_pg&wd=%E8%B0%B7%E6%AD%8C%E6%B5%8F%E8%A7%88%E5%99%A8%E4%B8%8B%E8%BD%BD&oq=%25E8%25B0%25B7%25E6%25AD%258C%25E6%25B5%258F%25E8%25A7%2588%25E5%2599%25A8%25E4%25B8%258B%25E8%25BD%25BD&rsv_pq=97c4ae6100042acb&rsv_t=f1a2AJ1xhp3JgNt65XxfFYZObeY1sxkWwyyyGJ6zuuw8j4PSsLKCDZAkhvU9XR3Kjcex&rqlang=cn&rsv_enter=0&prefixsug=%25E8%25B0%25B7%25E6%25AD%258C%25E6%25B5%258F%25E8%25A7%2588%25E5%2599%25A8%25E4%25B8%258B%25E8%25BD%25BD&rsp=0">安装</a></div>', {
                offset: 't',
                anim: 1,
                shade: 0.3,
                shadeClose: true,
                icon: 6,
                closeBtn: 0,
                area: ['50%', '60px'],
                time: 10000
            });
            return true;
        } else {
            return false;
        }
    },
    /**
     * 搜索
     */
    jiantingshurukuang: function () {
        var one = null;
        $('#tab_seach').on('input', function () {
            one = null;
            var val = $(this).val();
            if (own.util.trim(val) != '') {
                $('.layui-nav a').removeClass('seacha');
                var objs = $('.layui-nav a:contains(' + val + ')');
                objs.addClass('seacha');
                objs.each(function () {
                    if (one == null) {
                        if ($(this).attr('url') != undefined) {
                            one = this;
                        }
                    }
                });
                //同时标红当前iframe页面内容
                // var wind = $('.layui-tab-content .layui-show iframe')[0].contentWindow.document;
                // $(wind).find('*').removeClass('seachtext');
                // $(wind).find('*:contains('+val+'):first-child').addClass('seachtext');
            } else {
                $('.layui-nav a').removeClass('seacha');
                // var wind = $('.layui-tab-content .layui-show iframe')[0].contentWindow.document;
                // $(wind).find('*').removeClass('seachtext');
            }
        }).keyup(function (event) {
            if (event.keyCode == 13) {
                if (one != null) {
                    one.click();
                }
            }
        });
    },
    tabClose: function () {
        layui.element.on('tabDelete(index-tab)', function (data) {
            $('.layui-tab-content .layui-tab-item').eq(data.index).remove();
        });
    },
    /**
     * 刷新
     */
    refresh: function () {
        $('.layui-tab-content .layui-show iframe')[0].contentWindow.location.reload(true);
    },
    /**
     * 加载菜单
     */
    loadingMenu: function () {
        njzxw.load.show();
        njzxw.ajax({
            url: URL.INDEX.LOADMENU,
            fun: function (a, b) {
                if (a) {
                    var html = "<ul class=\"layui-nav layui-nav-tree\" id='menu_ul' lay-filter=\"menu_nav\">";
                    for (var i = 0; i < b.data.length; i++) {
                        if (b.data[i].menu == false) {
                            continue;
                        }
                        var nodes = b.data[i].nodes;
                        html += '<li class="layui-nav-item"><a class="" href="javascript:;">' + b.data[i].text + '</a>';

                        if (checkMenu(nodes)) {
                            html += getMenu(nodes);
                        }

                        html += '</li>';
                    }

                    $('.leftScoll1').on('click', '.layui-icon-add-1', function (e) {
                        window.clearTimeout(openNavObj);

                        //加入个人工作台
                        var menu_id = $(this).parent().attr('menu_id');
                        njzxw.ajax({
                            url: URL.INDEX.ADDWORKBENCH,
                            data: {
                                menu_id: menu_id
                            },
                            fun: function (a, b) {
                                if (a) {
                                    if (b.state == 1) {
                                        njzxw.alert({
                                            msg: '添加工作台成功'
                                        });
                                        index.loadWorkbench();
                                    } else {
                                        njzxw.alert({
                                            error: true,
                                            msg: '添加工作台失败'
                                        });
                                    }
                                } else {
                                    njzxw.alert({
                                        error: true,
                                        msg: '添加工作台失败'
                                    });
                                }
                            }
                        });

                        return false;
                    });

                    function getMenu(json) {
                        var htmlnode = '<dl class="layui-nav-child">';
                        for (var i = 0; i < json.length; i++) {
                            if (json[i].menu == false) {
                                continue;
                            }
                            var url = json[i].href;
                            var nodes = json[i].nodes;

                            if (checkMenu(nodes) || url == undefined || url == '') {
                                url = 'javascript:void(0);';
                            }
                            htmlnode += '<dd><a menu_id="' + json[i].id + '" menu_name="' + json[i].text + '" url="' + url + '">' + json[i].text + '<i title="添加到我的工作台" class="layui-icon layui-icon-add-1" style="\n' +
                                '    position: absolute;\n' +
                                '    right: 10px;\n' +
                                '    top: 0;\n' +
                                '"></i></a>';

                            if (checkMenu(nodes)) {
                                htmlnode += getMenu(nodes);
                            }
                            htmlnode += '</dd>';
                        }
                        htmlnode += '</dl>';
                        return htmlnode;
                    }

                    function checkMenu(json) {
                        for (var i = 0; i < json.length; i++) {
                            if (json[i].menu == true) {
                                return true;
                            }
                        }
                        return false;
                    }

                    $('#menu_ul').replaceWith(html);
                    layui.element.render('nav');

                    //延迟200毫秒执行打开窗口操作
                    var openNavObj = null;
                    layui.element.on('nav(menu_nav)', function (elem) {
                        openNavObj = window.setTimeout(function () {
                            $('.layout-zxw-left').getNiceScroll().resize();
                            var url = $(elem).attr('url');
                            var menu_name = $(elem).attr('menu_name');
                            var menu_id = $(elem).attr('menu_id');
                            if (url != undefined && url != '' && url != 'null' && url != null) {
                                index.loadTab(menu_id, menu_name, url);
                            }
                            $('#leftScoll').getNiceScroll(0).resize();
                        }, 200);
                    });
                    njzxw.load.hide();
                } else {
                    njzxw.alert({
                        msg: '请求出现未知错误，请重新刷新页面',
                        error: true
                    });
                }
            }
        });
    },
    /**
     * 加载工作台
     */
    loadWorkbench: function () {
        njzxw.ajax({
            url: URL.INDEX.GETMENUWORKBENCHLIST,
            data: {},
            fun: function (a, b) {
                if (a) {
                    if (b.state == 1) {
                        if (b.data.length == 0) {
                            var html = "<dl style=\"color: #b3adad;\" >暂无设置</dl>";
                            $('.workbench_body').html(html);
                        } else {
                            var html = "<dl>";
                            for (var i = 0; i < b.data.length; i++) {
                                html += '<dd onclick="index.loadTab(\'' + b.data[i].id + '\',\'' + b.data[i].menu_name + '\',\'' + b.data[i].menu_url + '\');return false;" ><a menu_id="' + b.data[i].id + '" menu_name="' + b.data[i].menu_name + '" url="' + b.data[i].menu_url + '">' + b.data[i].menu_name + '</a></dd>';
                            }
                            html += "</dl>";
                            $('.workbench_body').html(html);
                        }
                    } else {
                        njzxw.alert({
                            error: true,
                            msg: '工作台加载失败'
                        });
                    }
                } else {
                    njzxw.alert({
                        error: true,
                        msg: '添加加载失败'
                    });
                }
            }
        });
    },
    /**
     * 加载tab页面
     * @param id
     * @param name
     * @param url
     */
    loadTab: function (id, name, url, showClose) {
        if ($(".layui-tab-title li[lay-id='" + id + "']").size() != 0) {
            layui.element.tabChange('index-tab', id);
            index.loadIframe(id, url);
            index.locationTab(id, true);
            return;
        }
        layui.element.tabAdd('index-tab', {
            title: name,
            id: id,
            attr: url,
            content: '<iframe onload="index.iframeload();" id="iframeBody' + (id.replaceAll('\\.', '')) + '" src="' + url + '" frameborder="0" class="layui-ifame"></iframe>'
        });
        if (showClose == false) {
            $("li[lay-id='" + id + "']").addClass('tab-no-close-tab');
        }

        layui.element.tabChange('index-tab', id);
        index.loadIframe(id, url);

        index.locationTab(id);

        if ($(window).width() <= 768) {
            $('.layout-zxw-left').animate({
                width: 0
            }, 300, function () {
                index.refresh();
            });

            $('.layui-icon-shrink-right').removeClass('layui-icon-shrink-right').addClass('layui-icon-spread-left');
        }
    },
    locationTabX: 0,
    /**
     * 定位tab对应id的位置
     * @param id
     */
    locationTab: function (id, type) {
        window.setTimeout(function () {
            //动态更改宽度
            var h = 0;
            $("li[lay-id='" + id + "']").prevAll().each(function (i, n) {
                h += $(n).width() + 30;
            });
            h += type == true ? 0 : $("li[lay-id='" + id + "']").width() + 30;
            // console.log("---"+$("li[lay-id='"+id+"']").width());
            $(".layui-tab-title").getNiceScroll(0).doScrollLeft(h, 500);

            index.locationTabX = h;
            console.log(h);
        }, 200);
        //显示对应iframe
        $('.layui-tab-item').removeClass('layui-show');
        $('#iframeBody' + (id.replaceAll('\\.', ''))).parent().addClass('layui-show')
    },
    tabLR: {
        left: function () {
            var cont = $(".layui-tab-title .layui-this").prevAll('li');
            if (cont.size() <= 0) {
                var tabCon = $('.layui-tab-title li');
                cont = tabCon.eq(tabCon.size() - 1);
            }
            var id = cont.eq(0).attr('lay-id');
            console.log(cont.size() + "--" + index.nowTabId + "--" + id);
            layui.element.tabChange('index-tab', id);
            index.locationTab(id, true);
        },
        right: function () {
            var cont = $(".layui-tab-title .layui-this").nextAll('li');
            console.log("==:" + cont.size());
            if (cont.size() <= 0) {
                cont = $('.layui-tab-title li').eq(0);
            }
            var id = cont.eq(0).attr('lay-id');
            if (id != undefined) {
                layui.element.tabChange('index-tab', id);
                index.locationTab(id, true);
            }
        }
    },
    /**
     * 加载页面
     */
    loadIframe: function (id, url) {
        nowTabId = id;
        $('#refresha').attr('url', url);
        $('#refresha').attr('iframe-id', id);
    },
    /**
     * 刷新完毕
     */
    iframeload: function () {

    },
    /**
     * 监听tab点击事件
     */
    jianting_tab: function () {
        layui.element.on('tab(index-tab)', function (data) {
            var url = $(data.elem.context).attr('lay-attr');
            var id = $(data.elem.context).attr('lay-id');
            console.log(url + "--" + id);
            if (id != undefined && url != undefined) {
                // index.loadIframe(id,url);
                index.locationTab(id, true);
            }
        });
    },
    /**
     * 左边菜单切换
     */
    leftChange: function () {
        $('.qiehuan').click(function () {
            if ($('.layout-zxw-left').hasClass('layui-hide-xs')) {
                $('.layout-zxw-left').removeClass('layui-hide-xs');
                if ($(window).width() <= 768) {
                    $('.layout-zxw-left').css('width', 0)
                }
            }
            if ($('.layout-zxw-left').css('width') == '0px') {
                $('.layout-zxw-left').animate({
                    width: 220
                }, 300);
                $('.layui-icon-spread-left').removeClass('layui-icon-spread-left').addClass('layui-icon-shrink-right');
                $('.layui-zxw-logo').show();
            } else {
                $('.layout-zxw-left').animate({
                    width: 0
                }, 300, function () {
                    // index.refresh();
                });
                $('.layui-zxw-logo').hide();
                $('.layui-icon-shrink-right').removeClass('layui-icon-shrink-right').addClass('layui-icon-spread-left');
            }
        });
    },
    moveOut: function () {
        $('.layout-zxw-head .layui-nav-item').mouseout(function () {
            $(this).removeClass('layui-this');
        });
    },
    logout: function () {
        njzxw.alert({
            type: 'confirm',
            msg: '确定要退出吗？',
            fun: function (a) {
                a();
                njzxw.ajax({
                    url: URL.USER.LOGINOUT,
                    fun: function (a, b) {
                        if (a) {
                            if (b.state == 1) {
                                njzxw.alert({
                                    msg: '感谢使用，下次再见。',
                                    fun: function () {
                                        window.top.isLogin = 0;
                                        window.top.location.href = own.config.localhostPath + '/login.html';
                                    }
                                });
                            } else {
                                njzxw.alert({
                                    error: true,
                                    msg: b.msg
                                });
                            }
                        } else {
                            njzxw.alert({
                                error: true,
                                msg: '退出失败'
                            });
                        }
                    }
                });
            }
        });
    }
}